﻿using Microsoft.Phone.Controls;
using IkeCode.WP7.HQReader.Base;
using IkeCode.WP7.HQReader.ViewModel;
using System;
using System.Windows;
using GalaSoft.MvvmLight.Ioc;
using IkeCode.WP7.Toolkit.Base.Navigation;
using ImageTools.IO.Gif;

namespace IkeCode.WP7.HQReader.Views
{
    /// <summary>
    /// Fedd Page
    /// </summary>
    public partial class FeedPage : PhoneApplicationPage
    {
        bool IsFromTile { get; set; }
        Uri MainUri { get; set; }
        INavigationService nav;

        /// <summary>
        /// Default constructor
        /// </summary>
        public FeedPage()
        {
            InitializeComponent();
            nav = SimpleIoc.Default.GetInstance<INavigationService>();
            var vm = SimpleIoc.Default.GetInstance<MainViewModel>();
            this.MainUri = vm.MyUri;
            ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
        }

        /// <summary>
        /// Called when a page becomes the active page in a frame.
        /// </summary>
        /// <param name="e">Event data</param>
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            try
            {
                this.IsFromTile = false;
                if (NavigationContext.QueryString.ContainsKey("publisherId"))
                {
                    var viewModel = DataContext as FeedViewModel;
                    string publisherId = "";
                    NavigationContext.QueryString.TryGetValue("publisherId", out publisherId);
                    viewModel.PublisherId = new Guid(publisherId);
                    this.IsFromTile = true;
                }
            }
            catch {}
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (this.IsFromTile)
            {
                nav.NavigateTo(MainUri);
            }
            else
            {
                base.OnBackKeyPress(e);
            }
        }
    }
}